<?php

/**
 * ShippingService.php
 *
 * @copyright  2022 beikeshop.com - All Rights Reserved
 * @link       https://beikeshop.com
 * @author     TL <mengwb@guangda.work>
 * @created    2023-05-12 14:24:05
 * @modified   2023-05-12 14:24:05
 */

namespace Plugin\MultiSeller\Services\TotalServices;

use Beike\Seller\Repositories\SellerRepo;
use Beike\Seller\Repositories\SellerShippingRepo;
use Beike\Shop\Services\CheckoutService;

class ShippingService
{
    /**
     * @param CheckoutService $checkout
     * @return array|null
     * @throws \Exception|\Throwable
     */
    public static function getTotal(CheckoutService $checkout): ?array
    {
        $totalService   = $checkout->totalService;
        $address        = $totalService->getCurrentCart()->shippingAddress ?? $totalService->getCurrentCart()->guest_shipping_address;
        $zoneId         = $address['zone_id']                              ?? 0;
        foreach ($totalService->getSellerIds() as $sellerId) {
            $shipping  = SellerShippingRepo::getSellerShippingByZoneId($sellerId, $zoneId);
            $amount    = (float) SellerShippingRepo::getShippingFee($sellerId, $shipping, $totalService);
            // if (!currency_format($amount)) {
            //     continue;
            // }
            if ($sellerId == 0) {
                $sellerName = trans('MultiSeller::common.self');
            } else {
                $sellerName = SellerRepo::mapIdToStoreName()[$sellerId] ?? 'undefined';
            }
            $totalData = [
                'seller_id'     => $sellerId,
                'code'          => 'shipping',
                'title'         => trans('shop/carts.shipping_fee') . '-' . $sellerName,
                'amount'        => $amount,
                'amount_format' => currency_format($amount),
            ];

            $totalService->amount += $totalData['amount'];
            $totalService->totals[] = $totalData;
        }

        return $totalData;
    }

    /**
     * 通过配送方式获取插件编码
     *
     * @param $shippingMethod
     * @return string
     */
    public static function parseShippingPluginCode($shippingMethod): string
    {
        $methodArray = explode('.', $shippingMethod);

        return $methodArray[0];
    }
}
